package com.ujs.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ujs.eduservice.entity.EduSubject;
import com.ujs.eduservice.entity.excel.SubjectData;
import com.ujs.eduservice.service.EduSubjectService;
import com.ujs.servicebase.exception.GuliException;

/**
 * @author zhangshihao
 * @create 2023-08-06 10:46
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    // SubjectExcelListener不能交给spring进行管理，需要自己new，不能注入其它对象
    // 不能实现数据库的操作
    public EduSubjectService subjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }


    // 读取excel内容
    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        if (data == null) {
            throw new GuliException(20001, "文件数据为空");
        }
        // 判断一级分类
        EduSubject existedOneSubject = this.existOneSubject(data.getOneSubjectName());
        if (existedOneSubject == null) { // 没有相同的一级分类，进行添加
            existedOneSubject = new EduSubject();
            existedOneSubject.setParentId("0");
            existedOneSubject.setTitle(data.getOneSubjectName()); // 一级分类名称
            subjectService.save(existedOneSubject);
        }

        // 二级分类的父id
        String pid = existedOneSubject.getId();
        // 判断二级分类
        EduSubject existedTwoSubject = this.existTwoSubject(data.getTwoSubjectName(), pid);
        if (existedTwoSubject == null) { // 没有相同的一级分类，进行添加
            existedTwoSubject = new EduSubject();
            existedTwoSubject.setParentId(pid);
            existedTwoSubject.setTitle(data.getTwoSubjectName()); // 二级分类名称
            subjectService.save(existedTwoSubject);
        }
    }

    // 判断一级分类不能重复添加
    private EduSubject existOneSubject(String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name).eq("parent_id", "0");
        return subjectService.getOne(wrapper);
    }

    // 判断二级分类不能重复添加
    private EduSubject existTwoSubject(String name, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name).eq("parent_id", pid);
        return subjectService.getOne(wrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
